//
//  HTTPClient.swift
//  AFN(swift)
//
//  Created by 阿城 on 15/12/6.
//  Copyright © 2015年 阿城. All rights reserved.
//

import UIKit
import AFNetworking


enum HTTPClientRequestType : Int{
    case GET
    case POST
}

class HTTPClient: AFHTTPSessionManager {
    /// 单例
    static let shareManager: HTTPClient = {
        let manager = HTTPClient()
        manager.responseSerializer.acceptableContentTypes?.insert("text/plain")
        //manager.responseSerializer = AFJSONResponseSerializer()
       return manager
    }()
    
    /// 请求回调
    typealias backClosure = ((data: AnyObject?, error: NSError?) -> Void)?

    /// 普通网络请求
    ///
    /// - parameter type:     请求方式
    /// - parameter url:      请求接口
    /// - parameter paras:    请求参数
    /// - parameter callBack: 请求后回调
    func request(type: HTTPClientRequestType, url: String, paras: AnyObject?, callBack: backClosure){
        
        switch type{
        case .GET:
            GET(url, parameters: paras, success: { (_ , data) -> Void in
                callBack?(data: data, error: nil)
            }, failure: { (_ , error) -> Void in
                callBack?(data: nil, error: error)
            })
        case .POST:
            POST(url, parameters: paras, success: { (_ , data) -> Void in
                callBack?(data: data, error: nil)
            }, failure: { (_ , error) -> Void in
                callBack?(data: nil, error: error)
            })
        }
        
        
    }
    
    /// 上传单文件
    ///
    /// - parameter url:      接口
    /// - parameter paras:    参数
    /// - parameter data:     上传文件(二级制)
    /// - parameter name:     文件的字段名
    /// - parameter callBack: 回调
    func uploadSingle(url: String, paras: AnyObject?, data: NSData, name: String, callBack: backClosure){
        POST(url, parameters: paras, constructingBodyWithBlock: { (formData) -> Void in
            
           formData.appendPartWithFileData(data, name: name, fileName: "CQ", mimeType: "application/octet-stream")
            
        }, success: { (_, data) -> Void in
            callBack?(data: data, error: nil)
        }) { (_, error) -> Void in
            callBack?(data: nil, error: error)
        }
    }
    
    /// 多文件上传(相同类型)
    ///
    /// - parameter url:      接口
    /// - parameter paras:    参数
    /// - parameter datas:    上传文件(二级制数组)
    /// - parameter name:     文件的字段名
    /// - parameter callBack: 回调
    func uploadMultiSameTypeFile(url: String, paras: AnyObject?, datas: [NSData], name: String, callBack: backClosure){
        POST(url, parameters: paras, constructingBodyWithBlock: { (formData) -> Void in
            
            for (idx,data) in datas.enumerate(){
                formData.appendPartWithFileData(data, name: name, fileName: "CQ\(idx)", mimeType: "application/octet-stream")
            }
            
            }, success: { (_, data) -> Void in
                callBack?(data: data, error: nil)
            }) { (_, error) -> Void in
                callBack?(data: nil, error: error)
        }
    }
    
    /// 多文件上传(不同类型)
    ///
    /// - parameter url:      接口
    /// - parameter paras:    参数
    /// - parameter datas:    文件[String: NSData] [字段名:二级制]
    /// - parameter callBack: 回调
    func uploadMultiDifferTypeFile(url: String, paras: AnyObject?, datas: [String: NSData], callBack: backClosure){
        POST(url, parameters: paras, constructingBodyWithBlock: { (formData) -> Void in
            
                for (name,data) in datas{
                    formData.appendPartWithFileData(data, name: name, fileName: "CQ", mimeType: "application/octet-stream")
                }
            
            }, success: { (_, data) -> Void in
                callBack?(data: data, error: nil)
            }) { (_, error) -> Void in
                callBack?(data: nil, error: error)
        } 
    }
    
    
    
}

// MARK: - get UserInfo
extension HTTPClient{
    /// 获取token
    private func getAccessToken(code: String, complement: backClosure){
        
        let urlString = "https://api.weibo.com/oauth2/access_token"
        var dict: [String : AnyObject] = [String : AnyObject]()
        dict["client_id"] = AppKey
        dict["client_secret"] = AppSecret
        dict["grant_type"] = "authorization_code"
        dict["code"] = code
        dict["redirect_uri"] = Redirect_uri
        
        request(HTTPClientRequestType.POST, url: urlString, paras: dict, callBack: complement)
    }
    
    /// 获取用户信息
    private func getUserInfo(complement: backClosure){
        guard let
            token = SCUserInfoViewModel.shareInfoViewModel.userInfoMod?.access_token ,
            userId = SCUserInfoViewModel.shareInfoViewModel.userInfoMod?.uid else{
            printLog("no token")
            return
        }
        
        let urlString = "https://api.weibo.com/2/users/show.json"
        
        let dict = [
            "access_token" : token ,
            "uid" : userId]
        
        request(HTTPClientRequestType.GET, url: urlString, paras: dict, callBack: complement)
        
    }
    
    /// 获取用户数据(信息 加 token)
    ///
    /// - parameter code:     授权码
    func getUserData(code: String ,callBack :(seccess: Bool)->()){
        
        getAccessToken(code) { (data, error) -> Void in
            
            if error != nil{
                printLog(error)
                callBack(seccess: false)
                return
            }
            
            //printLog(data)
            SCUserInfoViewModel.shareInfoViewModel.userInfoMod = SCUserInfoModel(dict: data as! [String : AnyObject])
            //printLog(SCUserInfo.shareInfo.userInfoMod)
            
            //接受用户数据
            self.getUserInfo({ (data, error) -> Void in
                
                if error != nil {
                    printLog(error)
                    callBack(seccess: false)
                    return
                }
                //printLog(data)
                SCUserInfoViewModel.shareInfoViewModel.userInfoMod?.setValuesForKeysWithDictionary(data as! [String : AnyObject])
                SCUserInfoViewModel.shareInfoViewModel.saveInfo()
                callBack(seccess: true)
            })
            
        }
    }
    
    func postTextStatus(status: String, callBack :(seccess: Bool)->()){
        
        let urlString = "https://api.weibo.com/2/statuses/update.json"
        let paras = [
            "access_token" : SCUserInfoViewModel.shareInfoViewModel.token!,
            "status" : status
        ]
        request(HTTPClientRequestType.POST, url: urlString, paras: paras) { (data, error) -> Void in
            
            if error != nil{
                callBack(seccess: false)
            }else{
                callBack(seccess: true)
            }
        }
        
    }
    func postImage(status: String,data: NSData, callBack :(seccess: Bool)->()){
        
        let urlString = "https://upload.api.weibo.com/2/statuses/upload.json"
        let paras = [
            "access_token" : SCUserInfoViewModel.shareInfoViewModel.token!,
            "status" : status
        ]
        uploadSingle(urlString, paras: paras, data: data, name: "pic") { (data, error) -> Void in
            if error != nil{
                callBack(seccess: false)
            }else{
                callBack(seccess: true)
            }
        }
        
    }
    
    func postImageStatus(status: String,datas: [NSData], callBack :(seccess: Bool)->()){
        //https://api.weibo.com/2/statuses/upload_url_text.json
        let urlString = "https://upload.api.weibo.com/2/statuses/upload.json"
        let paras = [
            "access_token" : SCUserInfoViewModel.shareInfoViewModel.token!,
            "status" : status
        ]
        uploadMultiSameTypeFile(urlString, paras: paras, datas: datas, name: "pic") { (data, error) -> Void in
            if error != nil{
                callBack(seccess: false)
            }else{
                callBack(seccess: true)
            }
        }
        
    }
    
}

